<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">





  <link rel="alternate" href="/atom.xml" title="renhao" type="application/atom+xml">






<meta name="description" content="垂直水平居中方法讨论与实现">
<meta property="og:type" content="article">
<meta property="og:title" content="垂直水平居中">
<meta property="og:url" content="https://huangrenhao.gitee.io/2019/09/12/css-centerandmiddle/index.html">
<meta property="og:site_name" content="renhao">
<meta property="og:description" content="垂直水平居中方法讨论与实现">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-09-03T08:50:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="垂直水平居中">
<meta name="twitter:description" content="垂直水平居中方法讨论与实现">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://huangrenhao.gitee.io/2019/09/12/css-centerandmiddle/">





  <title>垂直水平居中 | renhao</title>
  








<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">renhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://huangrenhao.gitee.io/2019/09/12/css-centerandmiddle/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="renhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="renhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">垂直水平居中</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-12T16:18:17+08:00">
                2019-09-12
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/css/" itemprop="url" rel="index">
                    <span itemprop="name">css</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/09/12/css-centerandmiddle/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/09/12/css-centerandmiddle/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>垂直水平居中方法讨论与实现<a id="more"></a></p>
<h3 id="水平居中"><a href="#水平居中" class="headerlink" title="水平居中"></a>水平居中</h3><ul>
<li><p>文本、行内元素、行内块级元素：text-align（text-align只控制行内内容如何相对他的块父元素对齐）</p>
<p>简单快捷，容易理解，兼容性好，但只对行内内容有效，属性会继承影响到后代行内内容，当子元素宽度大于父元素宽度则无效。</p>
</li>
<li><p>单个块级元素：利用margin中auto，在margin有节余的同时如果左右margin设置了auto，将会均匀分配剩余空间。如果上下的margin设置了auto，其计算值为0。</p>
<p>缺点是必须定宽，并且值不能为auto，宽度要小于父元素（否则无效）。</p>
</li>
<li><p>多个块级元素：将块级元素display属性指定为行内或者行内块级形式，然后利用text-align控制行内块级元素来控制块级元素的水平居中。但块级元素改为inline-block换行、空格会产生元素间隔。</p>
</li>
<li><p>使用绝对定位：子元素绝对定位，父元素相对定位，top、right、bottom、left的值是相对于父元素尺寸的，margin和transform是相对于自身尺寸，组合使用达到水平居中。可以将left设为50%（父元素宽度的一半），然后将子元素向右平移50%（自身宽度的一半）。</p>
<p>不管是块级元素还是行内元素都可以实现，但是脱离了文档流。</p>
</li>
<li><p>任意个元素：flex，设置当前主轴的对齐方式为居中即<code>justify-content:center</code></p>
</li>
</ul>
<p>对于水平居中首先应该考虑哪些元素有自带的居中效果，即考虑行内元素或者行内块级元素，一般都以<code>text-align:center</code>，其次去考虑可不可以使用<code>margin:0 auto</code>，还是不行的话可以使用绝对定位或者flex布局，移动端能用flex就用flex。</p>
<h3 id="垂直居中"><a href="#垂直居中" class="headerlink" title="垂直居中"></a>垂直居中</h3><ul>
<li><p>单行文本、行内元素、行内块级元素：line-height（与height等值）。line-height最终表现是通过inline box实现，无论inline box所占的高度是多少其占据的空间都是与文字内容公用水平中垂线。缺点是只能作用于单行行内内容，并且需要知道高度的值。</p>
</li>
<li><p>多行文本、行内元素、行内块级元素：通过用span把所有文字包裹起来，设置display：inline-block将其转化为行内块级元素解决。外部<code>div</code>高度和文字大小比例<code>1.14</code>为宜</p>
</li>
<li><p>大小不固定的图片：<a href="https://www.zhangxinxu.com/wordpress/2009/08/%E5%A4%A7%E5%B0%8F%E4%B8%8D%E5%9B%BA%E5%AE%9A%E7%9A%84%E5%9B%BE%E7%89%87%E3%80%81%E5%A4%9A%E8%A1%8C%E6%96%87%E5%AD%97%E7%9A%84%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD/" target="_blank" rel="noopener">张鑫旭原文</a></p>
<ul>
<li><p>透明gif图片+背景定位：使用一个透明的gif图片做覆盖层，高宽拉伸至所需要的大小，然后给这个gif图片一个<code>background-position:center</code>的声明，将<code>background-image</code>写在页面上（css不支持动态URL地址）。</p>
</li>
<li><p><code>display:table-cell</code>和文字大小控制居中（淘宝团队采用的图片居中方法）：</p>
<pre><code>div {display:table-cell; width:144px; height:144px; font-size:118px; border:1px solid #beceeb; text-align:center; vertical-align:middle;}/*这里大小是根据宽高上限128像素图片设置*/
div img {vertical-align:middle}
</code></pre><p>这个方法的不足之处在于不支持<code>&lt;img&gt;</code>外标签的浮动，所以当多图片显示时需要再在外面嵌套一层标签（消耗资源）。</p>
</li>
<li><p><code>display:inline-blcok</code>和文字大小控制居中：使用<code>&lt;a&gt;</code>标签足以实现图片垂直居中的显示效果，关键是将<code>&lt;a&gt;</code>标签默认的<code>inline</code>属性值设置为<code>inline-block</code>，这样<code>&lt;a&gt;</code>标签既支持宽度又支持<code>vertical-align:middle</code>，配合<code>&lt;img&gt;</code>中的<code>vertical-align:middle</code>即可实现图片的水平垂直居中。</p>
<pre><code>a{display:inline-block; width:1.2em; font-size:128px; text-align:center; vertical-align:middle;}
a img{vertical-align:middle;}
</code></pre></li>
<li><p>可以在图片上设置<code>vertical-align:middle</code>（默认为基线对齐），然后在父元素中设置<code>line-height</code>与<code>height</code>相等，并设置<code>font-size</code>为0后才可以完全垂直居中。</p>
</li>
<li><p>透明图片拉伸对齐实现垂直居中显示：原理是将要显示的图片与一张高度100%、宽度1像素的透明图片<code>vertical-align:middle</code>对齐（别的图片应该也可以）。核心原理与利用<code>font-size</code>大小实现IE下图片垂直居中一致，将<code>font-size</code>设置得很大目的是撑开IE下默认文字空间的高度（性质类似于空格），然后通过<code>vertical-align:middle</code>让图片与这个空白空格空间垂直居中对齐，这里将这个看不见的文字空间实例成一张透明的gif图片，高度可以轻松设置为外部标签的高度，宽度压缩至最小，然后通过<code>vertical-align:middle</code>对齐。</p>
<pre><code>&lt;li&gt;
    &lt;img src=&quot;http://image.zhangxinxu.com/image/study/s/s128/mm1.jpg&quot; /&gt;&lt;img src=&quot;../image/pixel.gif&quot; /&gt;
&lt;/li&gt;
</code></pre><pre><code>li{height:128px; width:150px; padding:13px 0; float:left; margin-right:10px; border:1px solid #beceeb; text-align:center;}
li .alpha_img{height:100%; width:0; vertical-align:middle;}
li .show_img{vertical-align:middle;}
</code></pre></li>
</ul>
</li>
<li><p>单个块级元素：</p>
<ul>
<li><p>table-cell实现：设置父元素<code>display:table-cell;vertical-align:middle</code>。</p>
<p>缺点：设置<code>table-cell</code>的元素宽度和高度设置百分比无效，需要给它的父元素设置<code>display:table</code>才生效，<code>table-cell</code>不感知margin，在父元素上设置<code>table-row</code>等属性也会使其不感知height，设置float或position会对默认布局造成破坏，可以为之增加一个父div定义float等属性，内容溢出会自动撑开父元素。</p>
<p>优点：宽高不定，兼容性好（ie8+）。</p>
</li>
<li><p>使用绝对定位实现：原理是将子元素设置为绝对定位，父元素设置为相对定位，这里子元素的定位方式就是相对于父元素的即top、right、bottom、left的值是相对于父元素尺寸，margin、transform是相对于自身尺寸，组合使用达到垂直居中。主要方式有两种，这两种都需要指定子元素的高度值：</p>
<ul>
<li><p>一种是将子元素的<code>top</code>设置为<code>50%</code>（父元素高度的一半），然后使用<code>transform:translateY(-50%)</code>（自身高度的一半）或者使用<code>margin-top:-(自身高度的一半)</code>。两者各有优缺点，使用margin-top兼容性好（不管是块级元素还是行内元素都可以实现），但需要知道高度值，使用transform兼容性不好（ie9+）。</p>
</li>
<li><p>另一种是将子元素的<code>top</code>、<code>bottom</code>设置为0，然后设置<code>margin:auto 0</code>，这样margin-top和margin-bottom会自动占满父元素空间并且平分，兼容性较好（ie8+）。</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<ul>
<li>使用flex实现：设置父元素<code>display:flex</code>后可以在父元素上设置<code>align-items</code>属性为<code>center</code>或者在子元素上设置<code>align-slef</code>为<code>center</code>。</li>
</ul>
<ul>
<li><p>任意个元素（flex）</p>
<p>flex设置对齐方式，和当个块级元素使用flex实现方法相同。</p>
</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/09/12/css-vertical-align/" rel="next" title="vertical-align与line-height">
                <i class="fa fa-chevron-left"></i> vertical-align与line-height
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/09/13/css-float/" rel="prev" title="浮动">
                浮动 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">renhao</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">94</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#水平居中"><span class="nav-number">1.</span> <span class="nav-text">水平居中</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#垂直居中"><span class="nav-number">2.</span> <span class="nav-text">垂直居中</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">renhao</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">265.9k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '2P1xqUWiCoNm14MH4yhURlJi-gzGzoHsz',
        appKey: 'uJN0uagHIVgXtBO1OuLV9Ban',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
